package com.hncc.kumao.action;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hncc.kumao.biz.INetdiskAccessTokenBiz;
import com.hncc.kumao.biz.IOfflineDownloadTaskBiz;
import com.hncc.kumao.biz.ITransferTaskBiz;
import com.hncc.kumao.entity.BreakpointUploadTask;
import com.hncc.kumao.entity.NetdiskAccessToken;
import com.hncc.kumao.entity.OfflineDownloadTask;
import com.hncc.kumao.entity.OfflineDownloadTaskInfo;
import com.hncc.kumao.entity.OfflineDownloadTaskWait;
import com.hncc.kumao.entity.TransferTask;
import com.hncc.kumao.exception.KumaoException;
import com.hncc.kumao.tool.CheckNetdiskTokenTool;
import com.hncc.kumao.tool.SMBOperation;
import com.hncc.kumao.tool.UploadFileTool;
import com.hncc.kumao.util.ConstValue;
import com.hncc.kumao.util.OfflineDownloadUtils;

import javassist.compiler.ast.NewExpr;

/**
 * Action 
 * @author Administrator
 *
 */
public class OfflineDownloadTaskAction extends BaseAction {
    
    private IOfflineDownloadTaskBiz offlineDownloadTaskBiz;
    private INetdiskAccessTokenBiz netdiskAccessTokenBiz;
    private ITransferTaskBiz transferTaskBiz;
    private UploadFileTool uploadFileTool;
    
    //添加离线任务
    public void add() {
        try {
            //获取请求数据
            HttpServletRequest request = getRequest();
            String requestData = (String) request.getAttribute(ConstValue.REQUEST_DATA);
            String userId = (String) request.getAttribute(ConstValue.REQUEST_USER_ID);
            JSONObject jsonObject = JSON.parseObject(requestData);
            //解析出网盘令牌对象
            NetdiskAccessToken netdiskAccessToken = jsonObject.getObject("netdiskToken", NetdiskAccessToken.class);
            //解析出离线下载对象
            OfflineDownloadTask offlineDownloadTask = jsonObject.getObject("taskInfo", OfflineDownloadTask.class);
            try {
                //校验网盘令牌
                checkNetdiskAccessToken(netdiskAccessToken);
                //校验任务信息
                checkOfflineDownloadTask(offlineDownloadTask);
                //单独校验SMB网盘信息的有效性
                if(netdiskAccessToken.getNetdiskType() == ConstValue.NETDISK_TYPE_SMB) {
                    if(!SMBOperation.check(netdiskAccessToken, offlineDownloadTask.getFileUri())) {
                        throw new KumaoException("网盘信息无效，无法访问到目标网盘");
                    }                    
                }
            } catch (KumaoException e) {
                e.printStackTrace();
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, e.getMessage());
                return;
            }
            netdiskAccessToken.setUserId(userId);
            String netdiskId = netdiskAccessTokenBiz.add(netdiskAccessToken);
            
            offlineDownloadTask.setUserId(userId);
            //TODO 测试外键
            //offlineDownloadTask.setTargetNetdiskAccessTokenId(netdiskId);
            offlineDownloadTask.setNetdiskAccessToken(netdiskAccessToken);
            offlineDownloadTask.setState(ConstValue.OD_TASK_STATE_NEW);
            offlineDownloadTask.setCreateTime(new Date());
            if(offlineDownloadTask.getFileInfo() != null) {
                offlineDownloadTask.setFileInfoString(JSON.toJSONString(offlineDownloadTask.getFileInfo()));
            }
            if(offlineDownloadTask.getIsTransfer() == null) {
                offlineDownloadTask.setIsTransfer(0);
            }
            String taskId = offlineDownloadTaskBiz.add(offlineDownloadTask);
            
            //将离线下载任务存入Redis
            OfflineDownloadUtils.addNormalQueue(taskId);
            OfflineDownloadUtils.addUserTaskIdList(userId, taskId);
            //将离线下载任务信息存入Redis
            OfflineDownloadTaskInfo taskInfo = OfflineDownloadUtils.getTaskProgressRate(taskId);
            taskInfo.setTaskId(taskId);
            taskInfo.setCreateTime(offlineDownloadTask.getCreateTime());
            taskInfo.setState(offlineDownloadTask.getState());
            OfflineDownloadUtils.setTaskProgressRate(taskInfo);
            
            //将离线任务id返回
            jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, taskId);
        } catch (Exception e) {
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "服务器好像出了点问题");
            e.printStackTrace();
        }
    }
    
    //获取离线下载信息
    public void info() {
        try {
            HttpServletRequest request = getRequest();
            String requestData = (String) request.getAttribute(ConstValue.REQUEST_DATA);
            String userId = (String) request.getAttribute(ConstValue.REQUEST_USER_ID);
            String taskId = JSON.parseObject(requestData).getString("taskId");
            //根据任务id从数据库中获取对象
            OfflineDownloadTask offlineDownloadTask = offlineDownloadTaskBiz.get(taskId);
            String taskInfoJson = OfflineDownloadUtils.getTaskProgressRateJson(taskId);
            if(offlineDownloadTask == null || taskInfoJson == null || taskInfoJson.trim().length() <= 0) {
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "无此任务信息");
                return;
            }
            if(offlineDownloadTask.getUserId().equals(userId)) {
                //没问题，返回
                jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, JSON.parseObject(taskInfoJson));
                return;
            } else {
                //信息有误
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "任务id与令牌信息不匹配");
                return;
            }
        } catch (Exception e) {
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "服务器好像出了点问题");
            e.printStackTrace();
            return;
        }
    }
    
    //获取任务列表
    public void taskList() {
        try {
            HttpServletRequest request = getRequest();
            String requestData = (String) request.getAttribute(ConstValue.REQUEST_DATA);
            String userId = (String) request.getAttribute(ConstValue.REQUEST_USER_ID);
            //JSONObject jsonObject = JSON.parseObject(requestData);
            OfflineDownloadTask offlineDownloadTask = new OfflineDownloadTask();
            offlineDownloadTask.setUserId(userId);
            //获取任务列表
            List<OfflineDownloadTask> list = offlineDownloadTaskBiz.getList(offlineDownloadTask, null, null);
            List<OfflineDownloadTask> resultList = new ArrayList<OfflineDownloadTask>();
            for (OfflineDownloadTask task : list) {
                if(task.getState() != ConstValue.OD_TASK_STATE_DELETE && 
                        task.getState() != ConstValue.OD_TASK_STATE_CANCEL) {
                    OfflineDownloadTaskInfo taskInfo = OfflineDownloadUtils.getTaskProgressRate(task.getId());
                    task.setCurrentSize(taskInfo.getCurrentSize());
                    resultList.add(task);
                }
            }
            jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, resultList);
        } catch (Exception e) {
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "服务器好像出了点问题");
            e.printStackTrace();
            return;
        }
    }
    
    //获取进行中的任务列表
    public void progressTaskList() {
        try {
            HttpServletRequest request = getRequest();
            String userId = (String) request.getAttribute(ConstValue.REQUEST_USER_ID);
            List<OfflineDownloadTask> progressTaskList = new ArrayList<OfflineDownloadTask>();
            //获取该用户下所有任务id
            List<String> userTaskIdList = OfflineDownloadUtils.getUserTaskIdList(userId);
            //获取所有正在进行的任务id
            List<String> allTastList = new ArrayList<String>();
            List<String> normalQueue = OfflineDownloadUtils.getNormalQueue();
            List<String> retryQueue = OfflineDownloadUtils.getRetryQueue();
            List<String> normalTaskList = OfflineDownloadUtils.getNormalTask();
            List<String> retryTaskList = OfflineDownloadUtils.getRetryTask();

            List<OfflineDownloadTaskWait> retryWaitObjectList = OfflineDownloadUtils.getRetryWait();
            List<String> retryWaitList = new ArrayList<String>();
            for (OfflineDownloadTaskWait offlineDownloadTaskWait : retryWaitObjectList) {
                retryWaitList.add(offlineDownloadTaskWait.getTaskId());
            }
            
            //合并所有list
            allTastList.addAll(normalQueue);
            allTastList.addAll(retryQueue);
            allTastList.addAll(retryWaitList);
            allTastList.addAll(normalTaskList);
            allTastList.addAll(retryTaskList);
            
            for (String taskId : allTastList) {
                if(userTaskIdList.contains(taskId)) {
                    OfflineDownloadTask offlineDownloadTask = offlineDownloadTaskBiz.get(taskId);
                    OfflineDownloadTaskInfo offlineDownloadTaskInfo = OfflineDownloadUtils.getTaskProgressRate(taskId);
                    offlineDownloadTask.setCurrentSize(offlineDownloadTaskInfo.getCurrentSize());
                    progressTaskList.add(offlineDownloadTask);
                }
            }
            jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, progressTaskList);
        } catch (Exception e) {
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "服务器好像出了点问题");
            e.printStackTrace();
            return;
        }
    }
    
    //取消离线下载
    public void cancel() {
        try {
            HttpServletRequest request = getRequest();
            String requestData = (String) request.getAttribute(ConstValue.REQUEST_DATA);
            String userId = (String) request.getAttribute(ConstValue.REQUEST_USER_ID);
            String taskId = JSON.parseObject(requestData).getString("taskId");
            //根据任务id从数据库中获取对象
            OfflineDownloadTask offlineDownloadTask = offlineDownloadTaskBiz.get(taskId);
            String taskInfoJson = OfflineDownloadUtils.getTaskProgressRateJson(taskId);
            if(offlineDownloadTask == null || taskInfoJson == null || taskInfoJson.trim().length() <= 0) {
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "无此任务信息");
                return;
            }
            if(offlineDownloadTask.getUserId().equals(userId)) {
                
                switch (offlineDownloadTask.getState()) {
                case ConstValue.OD_TASK_STATE_NEW:
                    OfflineDownloadUtils.removeNormalQueue(taskId);
                    OfflineDownloadUtils.removeTaskProgressRate(taskId);
                    break;
                case ConstValue.OD_TASK_STATE_RELINK:
                    OfflineDownloadUtils.removeRetryQueue(taskId);
                    OfflineDownloadUtils.removeRetryWait(taskId);
                    OfflineDownloadUtils.removeTaskProgressRate(taskId);
                    break;
                case ConstValue.OD_TASK_STATE_GOING:
                    OfflineDownloadTaskInfo taskInfo = OfflineDownloadUtils.getTaskProgressRate(taskId);
                    taskInfo.setState(ConstValue.OD_TASK_STATE_CANCEL);
                    taskInfo.setTotalSize("0");
                    taskInfo.setCurrentSize("0");
                    taskInfo.setStartTime(null);
                    taskInfo.setEndTime(null);
                    OfflineDownloadUtils.setTaskProgressRate(taskInfo);
                    break;
                case ConstValue.OD_TASK_STATE_CANCEL:
                case ConstValue.OD_TASK_STATE_SUCCESS:
                case ConstValue.OD_TASK_STATE_REMOVE:
                case ConstValue.OD_TASK_STATE_FAIL:
                    OfflineDownloadUtils.removeTaskProgressRate(taskId);
                    String savePath = offlineDownloadTask.getFileSavePath();
                    if(savePath != null && savePath.trim().length() > 0) {
                        File file = new File(savePath);
                        if(file.exists()) {
                            file.delete();
                            File parentFile = file.getParentFile();
                            parentFile.delete();
                        }
                        offlineDownloadTask.setFileSavePath(null);
                    }
                    OfflineDownloadUtils.removeTaskProgressRate(taskId);
                    break;
                case ConstValue.OD_TASK_STATE_DELETE:
                    jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务已删除");
                    return;
                }
                offlineDownloadTask.setState(ConstValue.OD_TASK_STATE_CANCEL);
                offlineDownloadTaskBiz.update(offlineDownloadTask);
                
                jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, "取消成功");
                return;
            } else {
                //信息有误
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "任务id与令牌信息不匹配");
                return;
            }
        } catch (Exception e) {
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "服务器好像出了点问题");
            e.printStackTrace();
            return;
        }
    }
    
    //删除离线下载任务
    public void deleteTask() {
        try {
            HttpServletRequest request = getRequest();
            String requestData = (String) request.getAttribute(ConstValue.REQUEST_DATA);
            String userId = (String) request.getAttribute(ConstValue.REQUEST_USER_ID);
            String taskId = JSON.parseObject(requestData).getString("taskId");
            //根据任务id从数据库中获取对象
            OfflineDownloadTask offlineDownloadTask = offlineDownloadTaskBiz.get(taskId);
            String taskInfoJson = OfflineDownloadUtils.getTaskProgressRateJson(taskId);
            if(offlineDownloadTask == null || taskInfoJson == null || taskInfoJson.trim().length() <= 0) {
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "无此任务信息");
                return;
            }
            if(offlineDownloadTask.getUserId().equals(userId)) {
                
                switch (offlineDownloadTask.getState()) {
                case ConstValue.OD_TASK_STATE_NEW:
                    OfflineDownloadUtils.removeNormalQueue(taskId);
                    OfflineDownloadUtils.removeTaskProgressRate(taskId);
                    break;
                case ConstValue.OD_TASK_STATE_RELINK:
                    OfflineDownloadUtils.removeRetryQueue(taskId);
                    OfflineDownloadUtils.removeRetryWait(taskId);
                    OfflineDownloadUtils.removeTaskProgressRate(taskId);
                    break;
                case ConstValue.OD_TASK_STATE_GOING:
                    OfflineDownloadTaskInfo taskInfo = OfflineDownloadUtils.getTaskProgressRate(taskId);
                    taskInfo.setState(ConstValue.OD_TASK_STATE_DELETE);
                    taskInfo.setTotalSize("0");
                    taskInfo.setCurrentSize("0");
                    taskInfo.setStartTime(null);
                    taskInfo.setEndTime(null);
                    OfflineDownloadUtils.setTaskProgressRate(taskInfo);
                    break;
                case ConstValue.OD_TASK_STATE_CANCEL:
                case ConstValue.OD_TASK_STATE_SUCCESS:
                case ConstValue.OD_TASK_STATE_FAIL:
                case ConstValue.OD_TASK_STATE_REMOVE:
                    OfflineDownloadUtils.removeTaskProgressRate(taskId);
                    String savePath = offlineDownloadTask.getFileSavePath();
                    if(savePath != null && savePath.trim().length() > 0) {
                        File file = new File(savePath);
                        if(file.exists()) {
                            file.delete();
                            File parentFile = file.getParentFile();
                            parentFile.delete();
                        }
                        offlineDownloadTask.setFileSavePath(null);
                    }
                    OfflineDownloadUtils.removeTaskProgressRate(taskId);
                    break;
                case ConstValue.OD_TASK_STATE_DELETE:
                    jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务已删除");
                    return;
                }
                
                offlineDownloadTask.setState(ConstValue.OD_TASK_STATE_DELETE);
                offlineDownloadTaskBiz.update(offlineDownloadTask);
                
                jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, "删除成功");
                return;
            } else {
                //信息有误
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "任务id与令牌信息不匹配");
                return;
            }
        } catch (Exception e) {
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "服务器好像出了点问题");
            e.printStackTrace();
            return;
        }
    }
    
    //获取离线下载任务连接
    public void link() {
        try {
            HttpServletRequest request = getRequest();
            String requestData = (String) request.getAttribute(ConstValue.REQUEST_DATA);
            String userId = (String) request.getAttribute(ConstValue.REQUEST_USER_ID);
            String taskId = JSON.parseObject(requestData).getString("taskId");
            //根据任务id从数据库中获取对象
            OfflineDownloadTask offlineDownloadTask = offlineDownloadTaskBiz.get(taskId);
            String taskInfoJson = OfflineDownloadUtils.getTaskProgressRateJson(taskId);
            if(offlineDownloadTask == null || taskInfoJson == null || taskInfoJson.trim().length() <= 0) {
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "无此任务信息");
                return;
            }
            if(offlineDownloadTask.getUserId().equals(userId)) {
                
                switch (offlineDownloadTask.getState()) {
                case ConstValue.OD_TASK_STATE_NEW:
                case ConstValue.OD_TASK_STATE_RELINK:
                case ConstValue.OD_TASK_STATE_GOING:
                    jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务尚未完成");
                    return;
                case ConstValue.OD_TASK_STATE_CANCEL:
                    jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务已取消");
                    return;
                case ConstValue.OD_TASK_STATE_SUCCESS:
                    jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, offlineDownloadTask.getFileDownloadUrl());
                    return;
                case ConstValue.OD_TASK_STATE_FAIL:
                    jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务已失败");
                    return;
                case ConstValue.OD_TASK_STATE_REMOVE:
                    jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该文件已删除，请重新下载");
                    return;
                case ConstValue.OD_TASK_STATE_DELETE:
                    jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务以删除");
                    return;
                }
            } else {
                //信息有误
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "任务id与令牌信息不匹配");
                return;
            }
        } catch (Exception e) {
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "服务器好像出了点问题");
            e.printStackTrace();
            return;
        }
    }

    //转存离线下载任务
    public void transfer() {
        try {
            HttpServletRequest request = getRequest();
            String requestData = (String) request.getAttribute(ConstValue.REQUEST_DATA);
            String userId = (String) request.getAttribute(ConstValue.REQUEST_USER_ID);
            JSONObject jsonObject = JSON.parseObject(requestData);
            String taskId = jsonObject.getString("taskId");
            
            //根据任务id从数据库中获取对象
            OfflineDownloadTask offlineDownloadTask = offlineDownloadTaskBiz.get(taskId);
            
            //解析出网盘令牌对象
            NetdiskAccessToken netdiskAccessToken = jsonObject.getObject("netdiskToken", NetdiskAccessToken.class);
            netdiskAccessToken.setUserId(userId);
            String netdiskAccessTokenId = netdiskAccessTokenBiz.add(netdiskAccessToken);
            
            //解析出转存任务对象
            String targetFileUri = jsonObject.getString("transferInfo");
            TransferTask transferTask = new TransferTask();
            transferTask.setTargetFileUri(targetFileUri);
            transferTask.setOdTaskId(taskId);
            transferTask.setTargetNetdiskAccessTokenId(netdiskAccessToken.getId());
            transferTask.setState(ConstValue.TRANSFER_TASK_STATE_CREATE);
            transferTask.setCreateTime(new Date());
            String transferTaskId = transferTaskBiz.add(transferTask);
            transferTask = transferTaskBiz.get(transferTaskId);
            
            //判断改任务是否可以转存
            if(offlineDownloadTask.getIsTransfer() == ConstValue.OD_IS_TRANSFER_NO) {
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务不可以转存");
                return;
            }
            
            //校验网盘对象
            try {
                checkNetdiskAccessToken(netdiskAccessToken);
                //单独校验SMB网盘信息的有效性
                if(netdiskAccessToken.getNetdiskType() == ConstValue.NETDISK_TYPE_SMB) {
                    if(!SMBOperation.check(netdiskAccessToken, offlineDownloadTask.getFileUri())) {
                        throw new KumaoException("网盘信息无效，无法访问到目标网盘");
                    }                    
                }
            } catch (Exception e) {
                e.printStackTrace();
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, e.getMessage());
                return;
            }
            
            //判断任务与用户id是否匹配
            if(!offlineDownloadTask.getUserId().equals(userId)) {
                //信息有误
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "任务id与令牌信息不匹配");
                return;
            }
            
            //判断任务状态
            switch (offlineDownloadTask.getState()) {
            case ConstValue.OD_TASK_STATE_NEW:
            case ConstValue.OD_TASK_STATE_RELINK:
            case ConstValue.OD_TASK_STATE_GOING:
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务尚未完成");
                return;
            case ConstValue.OD_TASK_STATE_CANCEL:
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务已取消");
                return;
            case ConstValue.OD_TASK_STATE_FAIL:
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务已失败");
                return;
            case ConstValue.OD_TASK_STATE_REMOVE:
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该文件已删除，请重新下载");
                return;
            case ConstValue.OD_TASK_STATE_DELETE:
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务以删除");
                return;
            }
            
            //没问题，执行转存操作
            //设置并更新转存任务信息
            transferTask.setStartTime(new Date());
            transferTask.setState(ConstValue.TRANSFER_TASK_STATE_GOING);
            transferTaskBiz.update(transferTask);
            
            //构建一个断点上传任务对象
            BreakpointUploadTask breakpointUploadTask = new BreakpointUploadTask();
            breakpointUploadTask.setFileUri(transferTask.getTargetFileUri());
            
            if(netdiskAccessToken.getNetdiskType() == ConstValue.NETDISK_TYPE_SEAFILE) {
                String tempUri = transferTask.getTargetFileUri();
                String saveFileName = tempUri.substring(tempUri.lastIndexOf("/") + 1, tempUri.length());
                File transferFile = new File(ConstValue.BASE_RES_PATH + "/" + saveFileName);
                File downloadFile = new File(offlineDownloadTask.getFileSavePath());
                FileUtils.copyFile(downloadFile, transferFile);
                breakpointUploadTask.setFileServerPath(transferFile.getAbsolutePath());
            } else {
                breakpointUploadTask.setFileServerPath(offlineDownloadTask.getFileSavePath());
            }
            
            //调用工具类进行上传
            try {
                uploadFileTool.uploadFile(breakpointUploadTask, netdiskAccessToken);
            } catch (Exception e) {
                e.printStackTrace();
                //上传失败
                transferTask.setState(ConstValue.TRANSFER_TASK_STATE_FAIL);
                transferTask.setEndTime(new Date());
                transferTaskBiz.update(transferTask);
                if(netdiskAccessToken.getNetdiskType() == ConstValue.NETDISK_TYPE_SEAFILE) {
                    new File(breakpointUploadTask.getFileServerPath()).delete();
                }
                jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "转存失败");
                return;
            }
            //上传成功
            transferTask.setState(ConstValue.TRANSFER_TASK_STATE_SUCCESS);
            transferTask.setEndTime(new Date());
            transferTaskBiz.update(transferTask);
            if(netdiskAccessToken.getNetdiskType() == ConstValue.NETDISK_TYPE_SEAFILE) {
                new File(breakpointUploadTask.getFileServerPath()).delete();
            }
            jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, "转存成功");
            return;
        } catch (Exception e) {
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "服务器好像出了点问题");
            e.printStackTrace();
            return;
        }
    }
    
    //删除服务端文件
    public void deleteFile() {
        try {
            HttpServletRequest request = getRequest();
            String requestData = (String) request.getAttribute(ConstValue.REQUEST_DATA);
            String userId = (String) request.getAttribute(ConstValue.REQUEST_USER_ID);
            String taskId = JSON.parseObject(requestData).getString("taskId");
            //根据任务id从数据库中获取对象
            OfflineDownloadTask offlineDownloadTask = offlineDownloadTaskBiz.get(taskId);
            String taskInfoJson = OfflineDownloadUtils.getTaskProgressRateJson(taskId);
            if(offlineDownloadTask == null || taskInfoJson == null || taskInfoJson.trim().length() <= 0) {
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "无此任务信息");
                return;
            }
            if(offlineDownloadTask.getUserId().equals(userId)) {
                
                switch (offlineDownloadTask.getState()) {
                case ConstValue.OD_TASK_STATE_NEW:
                case ConstValue.OD_TASK_STATE_RELINK:
                case ConstValue.OD_TASK_STATE_GOING:
                    jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务尚未完成");
                    return;
                case ConstValue.OD_TASK_STATE_CANCEL:
                    jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务已取消");
                    return;
                case ConstValue.OD_TASK_STATE_SUCCESS:
                    String savePath = offlineDownloadTask.getFileSavePath();
                    if(savePath != null && savePath.trim().length() > 0) {
                        File file = new File(savePath);
                        if(file.exists()) {
                            file.delete();
                            File parentFile = file.getParentFile();
                            parentFile.delete();
                        }
                        offlineDownloadTask.setFileSavePath(null);
                        offlineDownloadTask.setState(ConstValue.OD_TASK_STATE_REMOVE);
                        offlineDownloadTaskBiz.update(offlineDownloadTask);
                    }
                    jsonReturn(true, ConstValue.RESULT_CODE_SUCCESS, "删除成功");
                    return;
                case ConstValue.OD_TASK_STATE_FAIL:
                    jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务已失败");
                    return;
                case ConstValue.OD_TASK_STATE_REMOVE:
                    jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该文件已删除，请重新下载");
                    return;
                case ConstValue.OD_TASK_STATE_DELETE:
                    jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "该任务以删除");
                    return;
                }
            } else {
                //信息有误
                jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "任务id与令牌信息不匹配");
                return;
            }
        } catch (Exception e) {
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "服务器好像出了点问题");
            e.printStackTrace();
            return;
        }
    }
    
    //校验网盘对象
    private void checkNetdiskAccessToken(NetdiskAccessToken netdiskAccessToken) {
        if(netdiskAccessToken == null) {
            throw new KumaoException("缺少网盘令牌信息");
        }
        if(netdiskAccessToken.getNetdiskType() == null) {
            throw new KumaoException("网盘类型不能为空");
        }
        if(netdiskAccessToken.getNetdiskUrl() == null || netdiskAccessToken.getNetdiskUrl().trim().length() <= 0) {
            if(netdiskAccessToken.getNetdiskType() != ConstValue.NETDISK_TYPE_BAIDU && 
                    netdiskAccessToken.getNetdiskType() != ConstValue.NETDISK_TYPE_JIANGUOYUN) {
                throw new KumaoException("网盘URL不能为空");
            }
        }
        if((netdiskAccessToken.getAccessToken() == null || netdiskAccessToken.getAccessToken().trim().length() <= 0)
                && (netdiskAccessToken.getUsername() == null || netdiskAccessToken.getUsername().trim().length() <= 0
                        || netdiskAccessToken.getPassword() == null || netdiskAccessToken.getPassword().trim().length() <= 0)
                && netdiskAccessToken.getTokenType() != ConstValue.TOKEN_TYPE_ANONYMITY) {
            throw new KumaoException("缺少访问网盘必要信息，请检查网盘令牌或用户名和密码");
        }
        
        if(!CheckNetdiskTokenTool.checkNetdiskToken(netdiskAccessToken)) {
            throw new KumaoException("网盘信息无效，无法访问到目标网盘");
        }
    }
    
    //校验任务信息
    private void checkOfflineDownloadTask(OfflineDownloadTask offlineDownloadTask) {
        if(offlineDownloadTask.getFileUri() == null || offlineDownloadTask.getFileUri().trim().length() <= 0) {
            throw new KumaoException("文件路径不能为空");
        }
        if(offlineDownloadTask.getFileUri() == null || offlineDownloadTask.getFileUri().trim().length() <= 0) {
            throw new KumaoException("文件路径不能为空");
        }
        if(offlineDownloadTask.getFileSize() == null || offlineDownloadTask.getFileSize().trim().length() <= 0) {
            throw new KumaoException("文件大小不能为空");
        }

    }
    
    public void setOfflineDownloadTaskBiz(IOfflineDownloadTaskBiz offlineDownloadTaskBiz) {
        this.offlineDownloadTaskBiz = offlineDownloadTaskBiz;
    }
    public void setNetdiskAccessTokenBiz(INetdiskAccessTokenBiz netdiskAccessTokenBiz) {
        this.netdiskAccessTokenBiz = netdiskAccessTokenBiz;
    }
    public void setTransferTaskBiz(ITransferTaskBiz transferTaskBiz) {
        this.transferTaskBiz = transferTaskBiz;
    }
    public void setUploadFileTool(UploadFileTool uploadFileTool) {
        this.uploadFileTool = uploadFileTool;
    }
}
